package com.xdf.xzymanagementsystem.controller;

import com.xdf.xzymanagementsystem.base.BaseController;
import com.xdf.xzymanagementsystem.dto.ColumnConfigDTO;
import com.xdf.xzymanagementsystem.entity.ResponseResult;
import com.xdf.xzymanagementsystem.enums.ResponseEnum;
import com.xdf.xzymanagementsystem.util.CustumDozerMapperUtils;
import com.xdf.xzymanagementsystem.util.Example;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.xdf.xzymanagementsystem.entity.SysUserTableConfig;
import com.xdf.xzymanagementsystem.service.SysUserTableConfigService;

/**
 * @Description : 配置记忆列宽后端实现
 * @Author : 张柯
 * @Date : 2020-12-31 15:23:24
 */
@Api(tags = "用户报表列参数配置")
@CrossOrigin
@RestController
@RequestMapping("/sysUserTableConfig")
@RequiresUser
@Slf4j
public class SysUserTableConfigController extends BaseController {

    @Autowired
    private SysUserTableConfigService service;
    @Autowired
    private CustumDozerMapperUtils util;

    /**
     * 列拖拽
     *
     * @param record
     * @return
     */
    @PutMapping("/modify/column")
    public ResponseResult<Void> columnResize(ColumnConfigDTO record) throws Exception {
        SysUserTableConfig config = util.transObject(record, SysUserTableConfig.class);
        config.setSysUserId(getLoginUserId());
        service.updateBySysUserIdMenuId(config);
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }

    /**
     * 列位置更改
     *
     * @param record
     * @return
     * @throws Exception
     */
    @PostMapping("/modify/reorder")
    public ResponseResult<Void> columnReorder(@RequestBody List<ColumnConfigDTO> record) throws Exception {
        List<SysUserTableConfig> list = util.transSourceToTarget(record, SysUserTableConfig.class);
        Integer loginUserId = getLoginUserId();
        list.stream().map(x -> {
            x.setSysUserId(loginUserId);
            return x;
        });
        for (SysUserTableConfig config : list) {
            if (StringUtils.isNotEmpty(config.getFieldName()))
                service.updateBySysUserIdMenuId(config);
        }
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }

    /**
     * 列重置
     *
     * @param sysMenuId
     * @return
     */
    @PutMapping("/reset/all")
    public Map<String, ColumnConfigDTO> resetConfig(Integer sysMenuId) throws Exception {
        Integer userLoginId = getLoginUserId();
        service.updateByExample(new Example().andEq("sys_menu_id", sysMenuId).andEq("sys_user_id", userLoginId),
                SysUserTableConfig.builder()
                        .fieldAlign("center")
                        .fieldWidth(100D)
                        .fieldHidden(false)
                        .build());
        return convent(service.listQuery(SysUserTableConfig.builder().sysMenuId(sysMenuId).sysUserId(userLoginId).build()));
    }

    /**
     * @Description : 获取记忆列宽
     * @Return : java.util.List
     * @Author : 张柯
     * @Date : 2020-12-31 15:23:24
     */
    @ApiOperation(value = "查询方法", httpMethod = "POST", notes = "自动生成的查询方法")
    @RequestMapping(value = "/calculate", method = RequestMethod.POST)
    public Map<String, ColumnConfigDTO> calculate(@RequestBody List<ColumnConfigDTO> record) throws Exception {
//        List<SysUserTableConfig> list = util.transSourceToTarget(record, SysUserTableConfig.class);
        List<SysUserTableConfig> list = util.columnConfigList2FieldConfigList(record);
        log.debug(list != null ? list.toString() : "NULL");
        Integer userLoginId = getLoginUserId();
        if (CollectionUtils.isEmpty(list)) return null;

        list.stream().map(x -> {
            System.out.println(x.getClass());
            x.setSysUserId(userLoginId);
            return x;
        }).filter(x -> x.getFieldName() != null).collect(Collectors.toList());

        Integer menuId = list.get(0).getSysMenuId();
        List<SysUserTableConfig> exists = Optional.ofNullable(
                service.listQuery(SysUserTableConfig.builder()
                        .sysUserId(userLoginId)
                        .sysMenuId(menuId).build())).orElse(new ArrayList<>());
        Set<String> s = exists.stream().map(x -> x.getFieldName()).collect(Collectors.toSet());
        List<SysUserTableConfig> notExist = list.stream().filter(x -> !s.contains(x.getFieldName())).collect(Collectors.toList());
        AtomicInteger i = new AtomicInteger(notExist.size());
        if (CollectionUtils.isNotEmpty(notExist)) {
            service.multiInsert(notExist.stream().map(x -> {
                if ("".equals(x.getFieldName()))
                    x.setFieldSerialNum(0);
                x.setSysUserId(userLoginId);
                x.setFieldAlign("center");
                if (x.getFieldHidden() == null)
                    x.setFieldHidden(false);
                if (x.getFieldWidth() == null)
                    x.setFieldWidth(100D);
                x.setFieldSerialNum(i.getAndIncrement());
                return x;
            }).collect(Collectors.toList()));
            exists.addAll(notExist);
        }
        return convent(exists);
    }

    /**
     * 转换数据类型
     *
     * @param list
     * @return
     */
    private Map<String, ColumnConfigDTO> convent(List<SysUserTableConfig> list) {
        if (CollectionUtils.isEmpty(list)) return null;
//        return list.stream().collect(
//                Collectors.toMap(
//                    x -> x.getFieldName(),
//                    (x -> util.transObject(x, ColumnConfigDTO.class)),
//                    ((x, y) -> x)
//                )
//        );
        // 2022年6月14日 15:54:50 自己手动写类型转换，避免上面代码报错
        return list.stream().collect(
                Collectors.toMap(
                        x -> x.getFieldName(),
                        (x -> sysUserTableConfig2ColumnConfigDTO(x)),
                        ((x, y) -> x)
                )
        );
    }

    private ColumnConfigDTO sysUserTableConfig2ColumnConfigDTO(SysUserTableConfig record){
        return ColumnConfigDTO.builder().field(record.getFieldName()).width(record.getFieldWidth()).hidden(record.getFieldHidden()).align(record.getFieldAlign())
                .sysMenuId(record.getSysMenuId()).serialNum(record.getFieldSerialNum()).build();
    }

    private SysUserTableConfig ColumnConfigDTO2SysUserTableConfig(ColumnConfigDTO record){
        SysUserTableConfig ret = new SysUserTableConfig();
        ret.setSysMenuId(record.getSysMenuId());
        ret.setFieldAlign(record.getAlign());
        ret.setFieldName(record.getField());
        ret.setFieldHidden(record.getHidden());
        ret.setFieldSerialNum(record.getSerialNum());
        ret.setFieldWidth(record.getWidth());

        return ret;
    }

    private List<SysUserTableConfig> ColumnConfigDTO2SysUserTableConfigs(List<ColumnConfigDTO> list){
        List<SysUserTableConfig> retList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            retList.add(ColumnConfigDTO2SysUserTableConfig(list.get(i)));
        }

        return retList;
    }

}